<template>
	<view class="shouye-container">
		<!-- 背景图 -->
		<image class="bg-img" src="https://yun.qiongtuyule.com/static/img/shouye/bg.png" mode="aspectFill"></image>

		<!-- 顶部栏 -->
		<view class="top-bar">
			<view class="title-area" @tap="onSwitchDevice">
				<text class="title">净昆达白蚁监测</text>
				<image class="down-arrow" src="https://yun.qiongtuyule.com/static/img/shouye/down.png"></image>
			</view>
			<!-- <view class="add-btn" @tap="onAddDevice">
				<image class="jiahao-img" src="https://yun.qiongtuyule.com/static/img/shouye/jiahao.png"
					mode="aspectFit"></image>
			</view> -->
		</view>

		<!-- 弹出菜单 -->
		<view v-if="showMenu" class="menu-popup">
			<view class="menu-item" @tap="clickScan">扫一扫</view>
			<view class="menu-item" @tap="addDevice">手动添加设备</view>
			<view class="menu-item" @tap="manageProjects">项目管理</view>
		</view>

		<!-- 项目弹窗 -->
		<view v-if="showProjectMenu" class="popup">
			<view class="popup-item" v-for="(item, index) in projectListWithTotal" :key="index"
				@tap="selectProject(item)">
				<view class="item-left">{{ item.name }}</view>
				<view class="item-right">{{ item.count }}</view>
			</view>

			<view class="popup-item manage" @tap="manageProjects">
				<view class="item-left">项目管理</view>
				<view class="item-right">
					<image src="https://yun.qiongtuyule.com/static/img/shouye/project_management.png"
						class="gear-icon" />
				</view>
			</view>
		</view>
		<!-- 项目Tab -->
		<view class="project-tabs-container">
			<swiper class="swiper" :display-multiple-items="2" :current="activeTab" @change="onSwiperChange">
				<swiper-item v-for="(item, idx) in projectTabs" :key="item.id" class="swiper-item">
					<view :class="['tab-item', { active: idx === activeTab }]" @tap="onTabClick(idx)">
						{{ item.name }}
					</view>
				</swiper-item>
			</swiper>

			<image @tap="toggleProjectMenu" class="list-icon"
				src="https://yun.qiongtuyule.com/static/img/shouye/1.png" />
		</view>

		<!-- 设备数量 -->
		<view class="device-count">
			设备数量：{{ deviceCount }}
		</view>

		<!-- 项目卡片 -->
		<view class="card-container">
			<view class="card" @tap="onProjectDetail(project)" v-for="(project, index) in showProjects" :key="index">
				<!-- 箭头 -->
				<view class="arrow-icon">
					<uni-icons type="arrowright" size="20" color="#000" />
				</view>

				<!-- 图片 -->
				<image class="card-image"
					:src="project.icon ? project.icon : 'https://yun.qiongtuyule.com/static/img/shouye/shebei.png'"
					mode="aspectFit" />

				<!-- 文本 -->
				<view class="card-title">{{ project.depart_name }}</view>
				<view class="card-subtitle">全部设备({{ project.deviceCount }})</view>
			</view>

		</view>

		<!-- 项目卡片 -->
		<!-- <view class="card-list">
			<view v-for="item in showProjects" :key="item.id" class="project-card" @tap="onProjectDetail(item)">
				<image class="project-img"
					:src="item.icon ? item.icon : 'https://yun.qiongtuyule.com/static/img/shouye/shebei.png'"></image>
				<image class="arrow-right" src="https://yun.qiongtuyule.com/static/img/shouye/right.png"></image>
				<view class="project-info">
					<text class="project-name">{{ item.depart_name }}</text>
					<view style="height: 8rpx;"></view>
					<text class="project-devices">全部设备({{ item.deviceCount }})</text>
				</view>
			</view>
		</view> -->

		<!-- 编辑按钮 -->
		<!-- <view class="edit-btn" @tap="onEdit">
			编辑
		</view> -->
		<uniFab ref='fab' :content="content" @trigger="trigger"></uniFab>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniFab from '@/components/uni-fab'
	export default {
		components: {
			uniFab
		},
		data() {
			return {
				showProjectMenu: false,
				selectedProject: '全部',
				projectList: [],
				showMenu: false,
				projectTabs: [],
				activeTab: 0,
				projects: [],
				content: [{
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con03.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con3.png',
					text: '创建项目',
					active: false
				}, {
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con01.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con1.png',
					text: '扫一扫',
					active: false
				}, {
					iconPath: 'https://yun.qiongtuyule.com/static/img/home-con02.png',
					selectedIconPath: 'https://yun.qiongtuyule.com/static/img/home-con2.png',
					text: '添加设备',
					active: false
				}],
			}
		},
		computed: {
			...mapState([
				"userInfo", "location"
			]),
			projectListWithTotal() {
				const total = this.projectList.reduce((sum, p) => sum + p.count, 0);
				return [{
					name: '全部',
					count: total,
					id: null
				}, ...this.projectList];
			},
			deviceCount() {
				if (this.activeTab === 0) {
					return this.projects.reduce((sum, p) => sum + p.deviceCount, 0)
				} else {
					return this.projects[this.activeTab - 1].deviceCount
				}
			},
			showProjects() {
				if (this.activeTab === 0) {
					return this.projects
				} else {
					return [this.projects[this.activeTab - 1]]
				}
			}
		},
		onShow() {
			if (this.userInfo.token == undefined) {
				this.loginOut();
				return
			}
			this.onList();
		},
		methods: {
			trigger(e) {
				let that = this
				if (e.index == 0) {
					uni.navigateTo({
						url: '/pages/shouye/detail_edit'
					})
				} else if (e.index == 1) {
					// 只允许通过相机扫码
					uni.scanCode({
						onlyFromCamera: true,
						success: function(res) {
							let code = res.result;
							uni.navigateTo({
								url: '/pages/workOrder/createDevice?code=' + code
							})
						}
					});
				} else if (e.index == 2) {
					uni.navigateTo({
						url: '/pages/workOrder/createDevice'
					})
				}
			},
			loginOut() {
				this.$lib.$store.commit('clearUserInfo')
				uni.reLaunch({
					url: '/pages/login/index'
				})
			},
			toggleProjectMenu() {
				this.showProjectMenu = !this.showProjectMenu;
				if (this.showMenu == true) {
					this.showMenu = false;
				}
			},
			selectProject(item) {
				this.selectedProject = item.name;
				this.showProjectMenu = false;

				// if (name === '全部') {
				// 		this.activeTab = 0;
				// 	} else {
				// 		const idx = this.projectTabs.findIndex(p => p.name === name);
				// 		if (idx !== -1) {
				// 			this.activeTab = idx;
				// 		}
				// }
				if (item.name === '全部') { // “全部”不跳转
					// this.activeTab = 0;
					return;
				}

				// const idx = this.projectTabs.findIndex(p => p.name === name);
				// if (idx !== -1) this.activeTab = idx;

				// 跳转到详情页，确保参数已编码
				uni.navigateTo({
					url: `/pages/shouye/detail_setting?project_id=${item.id}`
				});
			},
			manageProjects() {
				this.showProjectMenu = false;
				if (this.showMenu == true) {
					this.showMenu = false;
				}
				uni.navigateTo({
					url: '/pages/shouye/detail_edit'
				});
			},
			onSwitchDevice() {
				uni.showToast({
					title: '切换设备',
					icon: 'none'
				})
			},
			onAddDevice() {
				// uni.showToast({
				// 	title: '添加设备',
				// 	icon: 'none'
				// })
				this.showMenu = !this.showMenu;
				if (this.showProjectMenu == true) {
					this.showProjectMenu = false;
				}

			},
			addDevice() {
				this.showProjectMenu = false;
				if (this.showMenu == true) {
					this.showMenu = false;
				}
				uni.navigateTo({
					url: '/pages/workOrder/createDevice'
				})
			},
			clickScan() {
				// #ifdef MP-WEIXIN || APP-PLUS
				uni.authorize({
					scope: 'scope.camera',
					success: () => {
						this.scan();
					},
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '需要摄像头权限',
							success: res => res.confirm && uni.openSetting()
						});
					}
				});
				// #endif

				// #ifdef H5
				this.scan();
				// #endif
			},

			scan() {
				uni.scanCode({
					onlyFromCamera: false, // 允许从相册选择二维码
					scanType: ['qrCode', 'barCode'],
					success: res => {
						const result = res.result;
						console.log('扫码结果', result);

						// 方式1：跳转到本地页面并传参
						uni.navigateTo({
							url: `/pages/workOrder/createDevice?code=${encodeURIComponent(result)}`
						});

						// 方式2：如果是网址，直接跳转 WebView
						// if (result.startsWith('http')) {
						//   uni.navigateTo({
						//     url: `/pages/webview/index?url=${encodeURIComponent(result)}`
						//   });
						// }
					},
					fail: err => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},
			onTabClick(idx) {
				this.activeTab = idx
			},
			onShowAllProjects() {
				uni.showToast({
					title: '查看所有项目',
					icon: 'none'
				})
			},
			onProjectDetail(item) {
				// uni.showToast({
				// 	title: `进入${item.name}详情`,
				// 	icon: 'none'
				// })
				uni.navigateTo({
					url: `/pages/xunjian/project_list?id=${item.id}`
				})
			},
			onEdit() {
				uni.showToast({
					title: '正在编辑',
					icon: 'none'
				})
			},
			// 展示首页项目列表
			async onList() {
				let res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.homeList,
					data: {
						page: 1,
						limit: 10
					},
					needLogin: true
				})
				if (res.code === 1) {
					this.projects = res.data
					this.projectList = res.data.map(p => ({
						name: p.depart_name,
						count: p.deviceCount,
						id: p.id
					}));
					this.projectTabs = [{
						name: '全部',
						id: 0
					}, ...res.data.map((item, index) => ({
						name: item.depart_name,
						id: index + 1
					}))];
					this.$forceUpdate();
				}
			}
		}
	}
</script>

<style scoped>
	.project-tabs-container {
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		margin-top:40rpx;
	}

	.swiper {
		flex: 1;
		/* 占满剩余空间 */
		height: 80rpx;
	}

	.swiper-item {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.tab-item {
		padding: 0 20rpx;
		font-size: 28rpx;
		line-height: 80rpx;
	}

	.tab-item.active {
		color: #007aff;
		border-bottom: 2rpx solid #007aff;
	}

	.list-icon {
		width: 40rpx;
		height: 40rpx;
		margin-left: 20rpx;
	}

	.arrow-icon {
		float: right;
	}

	.card-container {
		margin-top: 40rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		gap: 20rpx;
		padding: 0 20rpx;
		/* 左右边距 */
	}

	.card {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 20rpx;
		width: 48%;
		box-sizing: border-box;
		margin-bottom: 20rpx;
		/* 行间距 */
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		position: relative;
	}


	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.card-image {
		width: 100rpx;
		height: 200rpx;
		margin: 0 auto;
	}

	.card-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-top: 10rpx;
	}

	.card-subtitle {
		color: gray;
		font-size: 24rpx;
	}

	.popup {
		position: absolute;
		right: 30rpx;
		top: 300rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
		width: 300rpx;
		z-index: 99;
	}

	.popup-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 26rpx 30rpx;
		font-size: 28rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.popup-item:last-child {
		border-bottom: none;
	}

	.popup-item.manage {
		font-weight: bold;
	}

	.gear-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.menu-popup {
		position: absolute;
		right: 30rpx;
		top: 220rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
		z-index: 99;
	}

	.menu-item {
		padding: 24rpx 40rpx;
		font-size: 28rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.menu-item:last-child {
		border-bottom: none;
	}

	.shouye-container {
		padding-top: 60rpx;
		position: relative;
		min-height: 100vh;
		overflow: hidden;
		background: transparent;
	}

	.bg-img {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		width: 100vw;
		height: 100vh;
		z-index: -999;
	}

	.top-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx 32rpx 0 32rpx;
		position: relative;
		z-index: 1;
	}

	.title-area {
		display: flex;
		align-items: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #222;
	}

	.down-arrow {
		width: 18rpx;
		height: 10rpx;
		margin-left: 15rpx;
	}

	.add-btn {
		width: auto;
		height: auto;
		background: none;
		border-radius: 0;
		box-shadow: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.jiahao-img {
		width: 38rpx;
		height: 38rpx;
		margin-right: 190rpx;
	}

	.project-tabs {
		display: flex;
		align-items: center;
		margin: 32rpx 0 0 32rpx;
		position: relative;
		z-index: 1;
	}

	.tab-item {
		font-size: 36rpx;
		color: #6f7180;
		margin-right: 10rpx;
		font-weight: normal;
		transition: color 0.2s;
	}

	.tab-item.active {
		color: #222;
		font-weight: bold;
		font-size: 36rpx;
	}

	.list-icon {
		width: 78rpx;
		height: 58rpx;
		margin-left: 95rpx;
	}

	.device-count {
		margin: 32rpx 0 0 32rpx;
		background: #8CAAC0;
		color: #fff;
		font-size: 32rpx;
		border-radius: 48rpx;
		padding: 30rpx 50rpx;
		display: inline-block;
		font-weight: bold;
		z-index: 1;
		position: relative;
	}

	.card-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		gap: 16rpx;
		/* 间距 */
		padding: 0 16rpx;
		/* 两侧留白 */
	}

	.project-card {
		min-width: 220rpx;
		max-width: 350rpx;
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);
		padding: 32rpx 24rpx 24rpx 24rpx;
		margin-bottom: 32rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-right: 16rpx;
		/* 添加右间距 */
	}

	.project-img {
		width: 56rpx;
		height: 126rpx;
		margin-bottom: 16rpx;
		margin-left: 36rpx;
	}

	.arrow-right {
		position: absolute;
		right: 24rpx;
		top: 32rpx;
		width: 10rpx;
		height: 22rpx;
	}

	.project-info {
		margin-top: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.project-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #222;
	}

	.project-devices {
		font-size: 28rpx;
		color: #bfc2cb;
		margin-top: 0rpx;
	}

	.edit-btn {
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 60rpx;
		background: #f5f5f7;
		color: #222;
		font-size: 28rpx;
		border-radius: 48rpx;
		padding: 16rpx 64rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
		z-index: 99;
	}
</style>